package com.tubeonfire.controller.admin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.gdata.data.youtube.UserEventEntry;
import com.tubeonfire.entity.Channel;
import com.tubeonfire.entity.Mission;
import com.tubeonfire.entity.Tube;
import com.tubeonfire.model.admin.ChannelModel;
import com.tubeonfire.model.admin.MissionModel;
import com.tubeonfire.model.admin.TubeModel;
import com.tubeonfire.search.TubeSearchModel;
import com.tubeonfire.service.YoutubeActiveService;
import com.tubeonfire.service.YoutubeBatchService;
import com.tubeonfire.service.YoutubeService;
import com.tubeonfire.util.ApplicationHelper;
import com.tubeonfire.util.TagHelper;
import com.tubeonfire.util.ViewCountHelper;

@SuppressWarnings("serial")
public class DoMissionServlet extends HttpServlet {

	private static final Logger log = Logger.getLogger(DoMissionServlet.class
			.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		try {
			String action = (String) req.getParameter("action");
			if (action != null && action.length() > 0) {
				if (action.equals("transport")) {
					Mission mission = MissionModel.getNotCompleteByType(2);
					if (mission != null) {
						YoutubeService tubeService = new YoutubeService();
						tubeService.setPage(mission.getSearchPage());
						tubeService.setLimit(mission.getSearchLimit());
						List<Tube> listToAdd = new ArrayList<Tube>();
						tubeService.searchByChannel(mission.getSearchKeyword(),
								true);
						Queue queue = QueueFactory.getDefaultQueue();					
						for (Tube tube : tubeService.getListResult()) {
							tube = processTubeDetail(mission.getPlaylistId(),
									tube);
							// add author to site.							
							queue.add(TaskOptions.Builder.withUrl(
									"/task-admin?action=add-author&uri="
											+ tube.getAuthorUrl()).method(
									TaskOptions.Method.GET));
							listToAdd.add(tube);
						}
						TubeModel.insert(listToAdd);
						if (tubeService.getListResult().size() > 0
								&& !tubeService.isTooManyRecentCallError()) {
							mission.setSearchPage(tubeService.getPage() + 1);
						} else {
							mission.setSearchPage(tubeService.getPage());
						}
						if (tubeService.getPage() == tubeService.getTotalPage()
								&& !tubeService.isTooManyRecentCallError()) {
							mission.setStatus(2);
						}
						MissionModel.insert(mission);
					}
				} else if (action.equals("follow")) {
					MissionModel model = new MissionModel();
					model.getListNotCompleteByType(1);
					List<Mission> listMission = model.getListResult();
					if (listMission != null && listMission.size() > 0) {
						YoutubeActiveService activeService = new YoutubeActiveService();
						for (Mission mission : listMission) {
							List<String> tubeIds = mission.getTubeIds();
							if (tubeIds.size() == 0) {
								activeService.getActiveByChannel(mission
										.getSearchKeyword());
								List<UserEventEntry> listResult = activeService
										.getListResult();
								if (listResult != null && listResult.size() > 0) {
									tubeIds = new ArrayList<String>();
									for (UserEventEntry entry : listResult) {
										tubeIds.add(entry.getVideoId());
									}
								}
								mission.setTubeIds(tubeIds);
								mission.setUpdated(Calendar.getInstance()
										.getTime());
								MissionModel.insert(mission);
							}
						}
					}
				} else if (action.equals("getFollow")) {
					MissionModel model = new MissionModel();
					model.getListNotCompleteByType(1);
					List<Mission> listMission = model.getListResult();
					if (listMission != null && listMission.size() > 0) {
						for (Mission mission : listMission) {
							if (mission != null && mission.getId().length() > 0) {
								List<String> tubeIds = new ArrayList<String>();
								for (String string : mission.getTubeIds()) {
									tubeIds.add(string);
								}
								List<String> listToAdd = new ArrayList<String>();
								if (mission.getTubeIds().size() > 0) {
									for (String tubeId : mission.getTubeIds()) {
										if (TubeSearchModel.getById(tubeId) == null) {
											if (listToAdd.size() != 50) {
												listToAdd.add(tubeId);
												tubeIds.remove(tubeId);
											} else {
												break;
											}
										}
									}
								}
								YoutubeBatchService.searchByListId(listToAdd,
										true);
								List<Tube> listTube = YoutubeBatchService
										.getListResult();
								Queue queue = QueueFactory.getDefaultQueue();	
								for (Tube tube : listTube) {
									tube = processTubeDetail(
											mission.getPlaylistId(), tube);
									// add author to site.							
									queue.add(TaskOptions.Builder.withUrl(
											"/task-admin?action=add-author&uri="
													+ tube.getAuthorUrl()).method(
											TaskOptions.Method.GET));
								}
								TubeModel.insert(listTube);
								mission.setTubeIds(tubeIds);
								mission.setUpdated(Calendar.getInstance()
										.getTime());
								MissionModel.insert(mission);
							}
						}
					} else {
						System.out.println("No tubeids");
					}
				} else if (action.equals("updateTubeView")) {
					if(ApplicationHelper.getApplicationType()==1){
						ViewCountHelper.updateDatabase(ViewCountHelper
								.getMapIdView());
					}					
				}
			}
		} catch (Exception e) {
			log.warning(e.getMessage());
			e.printStackTrace(System.err);
		}
	}

	private Tube processTubeDetail(String plId, Tube tube) {
		tube.setPlaylistId(plId);
		tube.setTags(TagHelper.youTag(tube.getTitle() + " "
				+ tube.getDescription()));
		tube.setOtherTags(TagHelper.getOtherTag(tube.getTags()));
		tube.setBumpPoint(Calendar.getInstance().getTimeInMillis() / 1000);
		if (ChannelModel.getById(tube.getChannelId()) == null) {
			Channel channel = new Channel();
			channel.setId(tube.getChannelId());
			channel.setTitle(tube.getChannelName());
			channel.setDescription(tube.getChannelName());
			channel.setDoc(Calendar.getInstance().getTime());
			channel.setUpdated(Calendar.getInstance().getTime());
			channel.setBumpPoint(Calendar.getInstance().getTimeInMillis() / 1000);
			channel.setStatus(1);
			ChannelModel.insert(channel);
		}
		return tube;
	}
}
